#include "graphtextview.h"

GraphTextView::GraphTextView(QWidget *window, GraphModelsList *list)
{
    graphsList = list;
    mainWindow = window;

    grid   = new QGridLayout(this);
    next   = new QPushButton("Next", this);
    prev   = new QPushButton("Prev", this);
    close  = new QPushButton("Close", this);
    visual = new QPushButton("Visual", this);

    buttonGrid = new QGridLayout(this);

    labelVertexEdges = new QLabel(this);
    labelGraphNo     = new QLabel(this);

    DrawWindow();
    InitSignalSlots();
}

GraphTextView::~GraphTextView() {
    delete grid;
    delete next;
    delete prev;
    delete close;
    delete visual;
    delete labelVertexEdges;
    delete labelGraphNo;
}

void GraphTextView::DrawWindow() {
    GraphModel curModel = graphsList->getGraphModel();
    int vertex = curModel.getVertexCount();
    int edges  = curModel.getEdgeCount();

    delete labelVertexEdges;
    delete labelGraphNo;

    for (int i = 0; i < grid->rowCount() - 1; ++i)
        for (int j = 0; j < grid->columnCount(); ++j)
            delete (grid->itemAtPosition(i, j))->widget();

    delete grid;
    grid = new QGridLayout(this);

    for (int i = 0; i < vertex; ++i)
        for (int j = 0; j < vertex; ++j) {
            QLabel *el = new QLabel(QString("%1").arg(curModel.getMatrixEl(i, j)));
            grid->addWidget(el, i, j);
        }

    labelVertexEdges = new QLabel(QString("Vertexes: %1, Edges: %2").arg(vertex).arg(edges));
    labelGraphNo     = new QLabel(QString("Graph: %1/%2").arg(graphsList->getGraphNum() + 1).arg(graphsList->size()), this);

    buttonGrid = new QGridLayout(this);
    buttonGrid->addWidget(labelVertexEdges, 0, 0, 1, 4);
    buttonGrid->addWidget(prev, 1, 0);
    buttonGrid->addWidget(close, 1, 1);
    buttonGrid->addWidget(visual, 1, 2);
    buttonGrid->addWidget(next, 1, 3);
    buttonGrid->addWidget(labelGraphNo, 2, 0);
    grid->addLayout(buttonGrid, vertex, 0, 1, vertex);
    this->show();
}

void GraphTextView::InitSignalSlots()
{
    QObject::connect(close,  SIGNAL(clicked()), this, SLOT(closeButtonEvent()));
    QObject::connect(next,   SIGNAL(clicked()), this, SLOT(nextButtonEvent()));
    QObject::connect(prev,   SIGNAL(clicked()), this, SLOT(prevButtonEvent()));
    QObject::connect(visual, SIGNAL(clicked()), this, SLOT(visualButtonEvent()));
}

void GraphTextView::closeButtonEvent()
{
    mainWindow->show();
    delete this;
}

void GraphTextView::nextButtonEvent()
{
    graphsList->increaseGraphNum();
    DrawWindow();
}

void GraphTextView::prevButtonEvent()
{
    graphsList->decreaseGraphNum();
    DrawWindow();
}

void GraphTextView::visualButtonEvent()
{
    GraphVisualView *visualViewWindow = new GraphVisualView(mainWindow, graphsList);
    delete this;
}
